//
//  PARemitMoneyViewController.m
//  PAMobileWallet
//
//  Created by Pay_SMP002 on 13-7-4.
//  Copyright (c) 2013年 平安付. All rights reserved.
//

#import "PARemitMoneyViewController.h"
#import "Global.h"
#import "PARemitMoneyView.h"
#import "PAPayAlertView.h"
#import "PATradeInfoCell.h"
#import "PAVerificationCodeViewController.h"
#import "PATradeInfo.h"
#import "PABaseTableViewCell.h"
#import "PADataCenter.h"
#import "PAUserInfo.h"
#import "PAHttpRequest.h"
#import "NSData+Extend.h"
#import "PAAsynImageView.h"
#import "PAAddCardViewController.h"
#import <UIKit/UIKit.h>
#import "PAChekText.h"
#import "PAStateType.h"

#define TradeInfoCellHeight 70

@interface PARemitMoneyViewController ()

@property(nonatomic, copy)NSString *tempFilePath;
@property(nonatomic, strong)AVAudioRecorder *recorder;
@property(nonatomic, assign)BOOL isRecording;

@end

@implementation PARemitMoneyViewController
@synthesize phoneNameStrT;
@synthesize phoneNumStrT;

@synthesize sendMoneyTotle;
@synthesize getMoneyTotle;

@synthesize tradeInfos              = _tradeInfos;
@synthesize refreshIndexPath;
@synthesize tempFilePath;
@synthesize recorder                = _recorder;
@synthesize isRecording;
@synthesize targetInfo              = _targetInfo;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self){
        self.tradeInfos = [[NSMutableArray alloc] initWithCapacity:0];
        
        remitMoneyView = [[PARemitMoneyView alloc] initWithFrame:RECT_PHONE];
        remitMoneyView.parentController = self;
        remitMoneyView.historyTradeTAB.delegate = self;
        remitMoneyView.historyTradeTAB.dataSource = self;
        self.view = remitMoneyView;
        
        navView = [[PANavView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
        navView.delegate = self;
        [navView setTitle:@"手机号转账"];
        [remitMoneyView addSubview:navView];
        
        payAlertView = [[PAPayAlertView alloc] init];
        payAlertView.PA_delegate = self;
        [remitMoneyView addSubview:payAlertView];
        payAlertView.hidden = YES;
        
        remitMoneyView.paytoContactTF.delegate = self;
        remitMoneyView.contextTF.delegate = self;
        remitMoneyView.contextpassTF.delegate = self;
        
        [self.view addSubview:payAlertView.alerView];
        payAlertView.alerView.hidden = YES;
        [self.view addSubview:payAlertView.unRegisterAlert];
        payAlertView.unRegisterAlert.hidden = YES;
    }
    return self;
}

#pragma mark - PANavViewDelegate methods

- (void)sendSelf:(PANavView *)sendView
{
    //初始化
    [navView setTitle:@"手机转账"];
    remitMoneyView.paytoContactTF.text = nil;
    [self restoredDefault];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)restoredDefault
{
    remitMoneyView.contextTF.text = @"";
    remitMoneyView.starPayBT.enabled = NO;
    [remitMoneyView.starPayBT setBackgroundImage:[UIImage imageNamed:@"确定01.png"] forState:UIControlStateNormal];
    
    remitMoneyView.contextpassTF.text = @"";
    remitMoneyView.starPaypassBT.enabled = NO;
    [remitMoneyView.starPaypassBT setBackgroundImage:[UIImage imageNamed:@"pay_payBT1.png"] forState:UIControlStateNormal];
}

- (void)testNext:(id)sender
{
    int tag = [(UIButton *)sender tag];
    if (tag == 1){
        [self showContact:sender];
    }
    else if (tag == 2){
        [remitMoneyView.contextTF resignFirstResponder];
    }
    else if (tag == 3){
        [self startPayT:sender];
    }
    else if (tag == 4){
        if (!verificationCodeController)
        {
            verificationCodeController = [[PAVerificationCodeViewController alloc] initWithNibName:nil bundle:nil];
            verificationCodeController.parentController = self;
        }
        [self.navigationController pushViewController:verificationCodeController animated:YES];
    }
}

- (void)voiceStartAction:(id)sender
{
    [remitMoneyView.contextTF resignFirstResponder];
}
- (void)payStartAction:(id)sender
{
    /*
    [self startPayT:sender];
     */
    
    NSMutableDictionary *postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType:@"op_query_balance"}];
    [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];
}

#pragma mark -
#pragma mark system methods

- (void)showContact:(UIButton *)sender
{
    picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.navigationBar.barStyle = UIBarStyleBlack;
    picker.peoplePickerDelegate = self;
	NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],
                               [NSNumber numberWithInt:kABPersonEmailProperty],
                               [NSNumber numberWithInt:kABPersonBirthdayProperty], nil];
    
	picker.displayedProperties = displayedItems;
    [self presentViewController:picker animated:YES completion:nil];
}
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    if (!phoneArray)
    {
        phoneArray = [[NSMutableArray alloc] initWithCapacity:10];
    }
    if ([phoneArray count]>0)
    {
        [phoneArray removeAllObjects];
    }
    if (!phoneNameArray)
    {
        phoneNameArray = [[NSMutableArray alloc] initWithCapacity:10];
    }
    if ([phoneNameArray count]>0)
    {
        [phoneNameArray removeAllObjects];
    }

    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    for (int k = 0; k<ABMultiValueGetCount(phone); k++)
    {
        //获取电话Label
        NSString * personPhoneLabel = (NSString*)CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k)));
        NSLog(@"personPhoneLabel ==== %@",personPhoneLabel);
        
        //获取該Label下的电话值
        NSString * personPhone = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, k));
        NSString * personPhoneT = [self checkPhoneNum:personPhone];
        if ([PAChekText validMobileNo:personPhoneT]==1 && [personPhoneT length]==11 && [personPhoneT length]>0) {
            [phoneArray addObject:personPhoneT];
        }
        
        NSString * nameString;
        
        if (ABRecordCopyValue(person, kABPersonLastNameProperty)&&(ABRecordCopyValue(person, kABPersonFirstNameProperty))== nil)
        {
            nameString = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
        }else if (ABRecordCopyValue(person, kABPersonLastNameProperty) == nil&&(ABRecordCopyValue(person, kABPersonFirstNameProperty)))
        {
            nameString = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        }else if (ABRecordCopyValue(person, kABPersonLastNameProperty)&&(ABRecordCopyValue(person, kABPersonFirstNameProperty)))
        {
            NSString *first =(NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
            NSString *last = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
            nameString = [NSString stringWithFormat:@"%@%@",last,first];
        }
        [phoneNameArray addObject:nameString];
    }
    
    if ([phoneArray count] > 0 && [phoneArray count] == 1)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
        self.phoneNumStrT = [phoneArray objectAtIndex:0];  //电话号码
        remitMoneyView.paytoContactTF.text = [self checkPhoneNum:self.phoneNumStrT];
        [self checkUserInfo:remitMoneyView.paytoContactTF.text];
    }
    
    if ([phoneArray count] > 1)
    {
        secletePersonalPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, iPhone5?(548-216+20):(460-216+20), 320, 216)];
        secletePersonalPicker.delegate=self;
        secletePersonalPicker.dataSource = self;
        secletePersonalPicker.showsSelectionIndicator=YES;
        [picker.view addSubview:secletePersonalPicker];
        
        [secletePersonalPicker reloadAllComponents];

        secletePersonalTB = [[UIToolbar alloc] initWithFrame:CGRectMake(0, iPhone5?(548-216-44+20):(460-216-44+20), 320, 44)];
        UIBarButtonItem * cancleButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:@selector(canclePicker)];
        UIBarButtonItem * placeHolderButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(completePicker)];

        [secletePersonalTB setItems:[NSArray arrayWithObjects: cancleButton,placeHolderButton, doneButton, nil]];
        [picker.view addSubview:secletePersonalTB];
    }
    
    if (phoneNameArray.count) {
        self.phoneNameStrT = [phoneNameArray objectAtIndex:0];
        [navView setTitle:[phoneNameArray objectAtIndex:0]];
    }
    
    return NO;
}
- (void)canclePicker
{
    [secletePersonalTB removeFromSuperview];
    [secletePersonalPicker removeFromSuperview];
}
- (void)completePicker
{
    [self dismissViewControllerAnimated:YES completion:nil];
    NSInteger row = [secletePersonalPicker selectedRowInComponent:0];
    [self checkPhoneNum:[phoneArray objectAtIndex:row]];
    remitMoneyView.paytoContactTF.text = [self checkPhoneNum:[phoneArray objectAtIndex:row]];
    if (phoneNameArray.count) {
        [navView setTitle:[phoneNameArray objectAtIndex:0]];
    }
    [secletePersonalTB removeFromSuperview];
    [secletePersonalPicker removeFromSuperview];
    [self checkUserInfo:remitMoneyView.paytoContactTF.text];
}
- (NSString *)checkPhoneNum:(NSString *)getString
{
    NSString * targetPhoneNumStr = getString;
    targetPhoneNumStr =[targetPhoneNumStr stringByReplacingOccurrencesOfString:@"(" withString:@""];
    targetPhoneNumStr =[targetPhoneNumStr stringByReplacingOccurrencesOfString:@")" withString:@""];
    targetPhoneNumStr =[targetPhoneNumStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    targetPhoneNumStr =[targetPhoneNumStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    return targetPhoneNumStr;
}

#pragma mark-
#pragma mark- UIPickerViewDataSource methods
//返回显示的列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

//返回当前列显示的行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [phoneArray count];
}

#pragma mark Picker Delegate Methods
//返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [phoneArray objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    remitMoneyView.paytoContactTF.text = [phoneArray objectAtIndex:row];
}

#pragma mark -
#pragma mark - system PAPayAlertViewDelegate methods
- (void)sendSelf:(PAPayAlertView *)sendView sendAlertView:(UIView *)sendAlertView sendButton:(UIButton *)sendButton;
{
    if (self.targetInfo) {
        if ([sendButton.titleLabel.text isEqualToString:@"确定"]){
            [self determinePay:sendButton];
        }else{  //取消
            payAlertView.hidden = YES;
            payAlertView.alerView.hidden = YES;
        }
    }else{
        payAlertView.hidden = YES;
        payAlertView.unRegisterAlert.hidden = YES;
        if ([sendButton.titleLabel.text isEqualToString:@"确定"]){
            [self determinePay:sendView.targetRealNameTF.text];
        }
    }
    [remitMoneyView startAnimition:remitMoneyView.payView];
}

- (BOOL) beforePayValidation
{
    if (!remitMoneyView.paytoContactTF.text )//|| !self.phoneNameStrT)
    {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"亲！您还没选择转账对象，请选择。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
        
        return FALSE;
    }
    
    
    
    return TRUE;
}

//点击支付，开始查询用户信息
- (void)startPayT:(id)sender
{
    if(![self beforePayValidation])
        return;
    else{
        if (self.targetInfo) {
            payAlertView.phoneNameLable.text = self.phoneNameStrT;//显示自己写的(或从通讯录得到的)人的名字
            //payAlertView.payMoneyLable.text = [NSString stringWithFormat:@"支付 %@ 元",remitMoneyView.contextTF.text]; //显示自己写的要转账的金额
            payAlertView.payMoneyLable.text = [NSString stringWithFormat:@"%@",remitMoneyView.contextTF.text]; //显示自己写的要转账的金额
            CGFloat floatWide = [self setWideForString:remitMoneyView.contextTF.text];
            payAlertView.payLable.frame = CGRectMake((578/2-60-floatWide)/2 , 3+86/2+40, 80/2 , 40);
            payAlertView.payMoneyLable.frame = CGRectMake((578/2-60-floatWide)/2+40 , 3+86/2+40, floatWide , 40);
            payAlertView.yuanLable.frame = CGRectMake((578/2-60-floatWide)/2+40+floatWide , 3+86/2+40, 40/2 , 40);

            [payAlertView.photoImageView setImgUrl:self.targetInfo.headImageUrl key:self.targetInfo.phoneNum digest:self.targetInfo.headImageDigest];
            payAlertView.hidden = NO;
            payAlertView.alerView.hidden = NO;
            /*
             *  不知为什么，需要再加一次，才看得到
             */
            [self.view addSubview:payAlertView.alerView];
            payAlertView.unRegisterAlert.hidden = YES;
        }else{
            /*
             *  不知为什么，需要再加一次，才看得到
             */
            payAlertView.hidden = NO;
            payAlertView.alerView.hidden = YES;
            payAlertView.unRegisterAlert.hidden = NO;
            [self.view addSubview:payAlertView.unRegisterAlert];
            [payAlertView loadUnRegisterWithAmount:remitMoneyView.contextTF.text phoneNum:remitMoneyView.paytoContactTF.text];
        }
    }
}
- (CGFloat)setWideForString:(NSString *)getString
{
    CGSize strSize = [getString sizeWithFont:[UIFont systemFontOfSize:20.0]];
    CGFloat lableWide = strSize.width+10;
    return lableWide;
}
//发送转账给某人的信息，开始校验
- (void)checkUserInfo:(NSString *)userPhoneNum
{
    PADataCenter *dataCenter = [PADataCenter sharedInstance];
    NSMutableDictionary *postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType: @"op_query_userinfo",k_loginId:dataCenter.self.selfInfo.baseInfo.account,k_targetPhoneNum:userPhoneNum}];
    [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];
}
//用户确认无误后，开始付款
- (void)determinePay:(id)sender
{
    PADataCenter *dataCenter = [PADataCenter sharedInstance];
    NSString *clientPaymentId = [self getClientPaymentId];
    NSString *commentStr = @"";
    
    NSData * data =[NSData dataWithContentsOfFile:[DocumentsPath stringByAppendingPathComponent:@"mediaComment.amr"]];
    if (data) {
        commentStr = [data base64Encoding];
    }
    NSString *targetAccount = self.targetInfo.account;
    NSString *targetPhoneNum = self.targetInfo.phoneNum;
    NSString *realName = @"";
    if (self.targetInfo) {
        realName = self.targetInfo.realName;
    }else{
        realName = [sender isKindOfClass:[NSString class]]?sender:@"";
    }
//    (nil == self.targetInfo.realName || [self.targetInfo.realName isEqualToString:@""])?realName = sender :self.targetInfo.realName;
    if (targetPhoneNum == nil) targetPhoneNum = remitMoneyView.paytoContactTF.text;
    if (targetAccount == nil) targetAccount = targetPhoneNum;
    NSMutableDictionary *postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType: @"op_pay",k_loginId:dataCenter.selfInfo.baseInfo.account,k_tradeType:[NSNumber numberWithInt:TT_Remit_Trade],k_payAmount:remitMoneyView.contextTF.text,k_payPassword:remitMoneyView.contextpassTF.text,k_mediaType:@"1",k_mediaComment:commentStr,k_clientPaymentId:clientPaymentId,k_targetId:targetAccount,k_targetPhoneNum:targetPhoneNum,k_targetRealName:realName}];
    
    [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:@{k_tradeId: clientPaymentId} delegate:self];
    
    /*
     *  为了唯一标识本地正在发送中的 交易记录，免去新增冗余字段
     *  将 clientPaymentId 临时保存在 tradeId 中
     */
    [postingDic setObject:clientPaymentId forKey:k_tradeId];
    [postingDic setObject:[NSNumber numberWithInt:TST_Sending] forKey:k_tradeStatus];
    [postingDic setObject:[NSNumber numberWithInt:TDT_Out] forKey:k_tradeDirection];
    [postingDic setObject:[NSNumber numberWithDouble:[remitMoneyView.contextTF.text doubleValue]] forKey:@"tradeAmount" ];
    PATradeInfo *newTrade = [[PATradeInfo alloc] initWithDic:postingDic];
    [self.tradeInfos addObject:newTrade];
    NSArray *indexPaths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:self.tradeInfos.count-1 inSection:0]];
    [remitMoneyView.historyTradeTAB insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];
    [self scrollDown];
}
#pragma mark - PANetworkDelegate
- (void)paRequestStarted:(NSDictionary *)userInfo
{
    NSString *operationType = [userInfo objectForKey:k_operationType];
    if ([operationType isEqualToString:@"op_pay"]) {
        
        payAlertView.hidden = YES;
        payAlertView.alerView.hidden = YES;
        payAlertView.targetRealNameTF.text = @"";
    }
}
- (void)paRequestRespons:(NSDictionary *)responsDic userInfo:(NSDictionary *)userInfo
{
    PADataCenter *dataCenter = [PADataCenter sharedInstance]; 
    NSString *op = [responsDic objectForKey:k_operationType];
    if ([op isEqualToString:@"op_query_balance"]){
        NSString * availableBalance = [responsDic objectForKey:K_availableBalance]; //目前可用余额
        double availableBalanceDouble = [availableBalance doubleValue];
        
        if (availableBalanceDouble < [remitMoneyView.contextTF.text doubleValue] && dataCenter.selfInfo.bankCardInfos.count == 0){ //支付金额和账户余额做对比
            PABaseViewController * controller = nil;
            if (!addCardController){
                [remitMoneyView startAnimition:remitMoneyView.paypassView];
                addCardController = [[PAAddCardViewController alloc] initWithNibName:nil bundle:nil];
                addCardController.parentController = self;
            }
            controller = addCardController;
            [[PAStateType sharedInstance] setValue:@"30" forKey:@"personalOrCharge"];
            [self.navigationController pushViewController:controller animated:YES];
            //去开通快捷界面
        }
        else{
            [remitMoneyView startAnimition:remitMoneyView.paypassView];
            [remitMoneyView.contextpassTF becomeFirstResponder];
        }
    }
    else if ([op isEqualToString:@"op_query_userinfo"]){
        NSDictionary * userInfoDic = [responsDic objectForKey:@"userInfo"];
        _targetInfo = [[PAUserInfo alloc] initWithDic:userInfoDic];
        NSString * realName = [userInfoDic objectForKey:@"realName"];
        [navView setTitle:realName];
        self.phoneNameStrT = realName;
        remitMoneyView.paytoContactTF.text = _targetInfo.phoneNum;
        payAlertView.phoneNameLable.text = self.phoneNameStrT; //显示返回的人的名字
        
        [self getCurrentData];
        
        NSMutableDictionary *postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType: @"op_query_trade",k_loginId:dataCenter.selfInfo.baseInfo.account,k_tradeType:[NSNumber numberWithInt:2],k_targetId:self.targetInfo.account,k_startDate:@"",k_endDate:@"",@"pageIndex":[NSNumber numberWithInt:1],@"pageSize":[NSNumber numberWithInt:100]}];
        [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];
    }
    else if ([op isEqualToString:@"op_query_trade"]){
        NSMutableArray * tradeArray = [responsDic objectForKey:@"historyTradeInfos"];
        [self cacheTradInfosForSelfAccount:dataCenter.selfInfo.baseInfo.account targetAccount:self.targetInfo.account tradeInfos:tradeArray];
        self.getMoneyTotle = [responsDic objectForKey:@"totalIncom"];
        self.sendMoneyTotle = [responsDic objectForKey:@"totalOut"];
        
        remitMoneyView.payMoneyLable.text = [NSString stringWithFormat:@"%.2f",[self.getMoneyTotle floatValue]];
        remitMoneyView.sendMoneyLable.text = [NSString stringWithFormat:@"%.2f",[self.sendMoneyTotle floatValue]];
        
        [self.tradeInfos removeAllObjects];
        for (NSDictionary *dic in tradeArray) {
            PATradeInfo * patradeInfo = [[PATradeInfo alloc] initWithDic:dic];
            [self.tradeInfos addObject:patradeInfo];
        }
                
        remitMoneyView.firstTopView.hidden = YES;
        remitMoneyView.havetradeTopView.hidden = NO;
        [remitMoneyView.historyTradeTAB reloadData];
        
    }
    else if ([op isEqualToString:@"op_pay"]){
        /*
        remitMoneyView.contextTF.text = @"";
        remitMoneyView.contextpassTF.text = @"";
         */
        [self restoredDefault];
        [remitMoneyView.contextTF becomeFirstResponder];
        
        NSError *error = nil;
        [[NSFileManager defaultManager] removeItemAtPath:[DocumentsPath stringByAppendingPathComponent:@"mediaComment.amr"] error:&error];
        [[NSFileManager defaultManager] removeItemAtPath:[DocumentsPath stringByAppendingPathComponent:@"mediaComment.wav"] error:&error];
        NSDictionary * tradeDictionary = [responsDic objectForKey:@"tradeInfo"];
        
        [remitMoneyView.starVoiceBT setBackgroundImage:[UIImage imageNamed:@"pay_voiceStar.png"] forState:UIControlStateNormal];

        NSString *tradeId = [userInfo objectForKey:k_tradeId];

        PATradeInfo *newTradeInfo = [[PATradeInfo alloc] initWithDic:tradeDictionary];
        NSUInteger index = [self indexOfLocalWithTradeId:tradeId];
        if (index == INT16_MAX) {
            [self.tradeInfos addObject:newTradeInfo];
            NSArray *indexPaths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:self.tradeInfos.count-1 inSection:0]];
            [remitMoneyView.historyTradeTAB insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationRight];
        }else{
            [self.tradeInfos replaceObjectAtIndex:index withObject:newTradeInfo];
            NSArray *indexPaths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:self.tradeInfos.count-1 inSection:0]];
            [remitMoneyView.historyTradeTAB reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationRight];
        }
        if (newTradeInfo.tradeStatus == TST_Success) {
            dataCenter.selfInfo.availableBalance -= newTradeInfo.tradeAmount;
            
            float tradeSendMoney = [self.sendMoneyTotle floatValue] + newTradeInfo.tradeAmount;
            remitMoneyView.sendMoneyLable.text = [NSString stringWithFormat:@"%.2f",tradeSendMoney];
        }
        
        /*
         *  交易金额变化、余额变化、timeLineInfo变化
         */
        NSDictionary *postingDic = @{k_operationType: @"op_query_balance"};
        [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:nil];
        postingDic = @{k_operationType:@"op_query_last_payment_info",@"pageIndex":[NSNumber numberWithInt:1],@"pageSize":[NSNumber numberWithInt:100]};
        [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:nil];
    }
    [self scrollDown];
}
- (void)paRequestAccurateFailed:(NSInteger)errorCode userInfo:(NSDictionary *)userInfo
{
    PADataCenter *dataCenter = [PADataCenter sharedInstance]; 
    NSString *op = [userInfo objectForKey:k_operationType];
    if ([op isEqualToString:@"op_pay"]) {
        NSString *tradeId = [userInfo objectForKey:k_tradeId];
        NSUInteger index = [self indexOfLocalWithTradeId:tradeId];
        if (index == INT16_MAX) {
            
        }else{
            PATradeInfo *tradeInfo = [self.tradeInfos objectAtIndex:index];
            tradeInfo.tradeStatus = TST_Failed;
            NSArray *indexPaths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:self.tradeInfos.count-1 inSection:0]];
            [remitMoneyView.historyTradeTAB reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationRight];
        }
    }else if ([op isEqualToString:@"op_query_userinfo"]){
        if (errorCode == 1025) {
            NSString *targetId = self.targetInfo.account;
            if (targetId == nil || [targetId isEqualToString:@""]) {
                targetId = remitMoneyView.paytoContactTF.text;
            }else{
                remitMoneyView.paytoContactTF.text = targetId;
            }
            NSMutableDictionary *postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType: @"op_query_trade",k_loginId:dataCenter.selfInfo.baseInfo.account,k_tradeType:[NSNumber numberWithInt:2],k_targetId:targetId,k_startDate:@"",k_endDate:@"",@"pageIndex":[NSNumber numberWithInt:1],@"pageSize":[NSNumber numberWithInt:100]}];
            [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];
            self.targetInfo = nil;
            [navView setTitle:targetId];
        }

    }
}

- (void)scrollDown
{
	CGFloat y = remitMoneyView.historyTradeTAB.contentSize.height - remitMoneyView.historyTradeTAB.bounds.size.height;
	if (y > 0) {
		[remitMoneyView.historyTradeTAB setContentOffset:CGPointMake(0, y) animated:YES];
	}
}

- (void)getCurrentData
{
    NSDate * senddate = [NSDate date];
    NSDateFormatter  *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd"];
    NSString * morelocationString = [dateformatter stringFromDate:senddate]; //现在时间
    endData = morelocationString;
    
    NSString * lastMonthStr = [senddate dateByAddingTimeInterval:-2*3600*24]; //上个月时间
    startDate = lastMonthStr;
}

- (void)sendMarkType:(int)getMarkType
{
    markType = getMarkType;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [remitMoneyView.contextTF becomeFirstResponder];

    if (markType == 10) {
        remitMoneyView.paytoContactTF.enabled = NO;
    }else{
        remitMoneyView.paytoContactTF.enabled = YES;
    }
    payAlertView = [[PAPayAlertView alloc] init];
    payAlertView.PA_delegate = self;
    [remitMoneyView addSubview:payAlertView];
    payAlertView.hidden = YES;
    
    remitMoneyView.commentLAB.text = @"请录入付款理由";

    UITapGestureRecognizer* singleRecognizer;
    singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFrom:)];
    [remitMoneyView.historyTradeTAB addGestureRecognizer:singleRecognizer];
}

- (void)handleSingleTapFrom:(UITapGestureRecognizer*)recognizer
{
    remitMoneyView.historyTradeTAB.frame = CGRectMake(0, 44 + 45, 320, (iPhone5?548:460) - 112/2 - 44 - 45);

    [remitMoneyView.paytoContactTF resignFirstResponder];
    [remitMoneyView.contextTF resignFirstResponder];
    [remitMoneyView.contextpassTF resignFirstResponder];

    [self startAnimitionT:remitMoneyView.payView snedType:1];
    [self startAnimitionT:remitMoneyView.paypassView snedType:1];

    remitMoneyView.recordVoiceBgIV.hidden = YES;
    remitMoneyView.recordVoiceBTN.hidden = YES;
    remitMoneyView.commentLAB.hidden = YES;
}

//1:下降 2： 上升    //键盘下去 view也跟着下去
- (void)startAnimitionT:(UIView *)sender snedType:(int)getType
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve: UIViewAnimationCurveLinear];
    [UIView setAnimationDuration:0.1];
    [UIView setAnimationDelegate:self];
    
    CGRect receiveViewRect = sender.frame;
    if (getType == 1)
    {
        receiveViewRect.origin.y = iPhone5?(548-56):(460-56);
    }
    else if (getType == 2)
    {
        receiveViewRect.origin.y = (iPhone5?568:480) - 216 - 112/2 -20;
    }
    sender.frame = receiveViewRect;

    [UIView commitAnimations];
}

- (void)playVoiceAction:(UITableViewCell *)celll
{
//    NSIndexPath *indexpath = [remitMoneyView.historyTradeTAB indexPathForCell:celll];
    PATradeInfoCell *cell = (PATradeInfoCell *)celll;
    cell.voiceCommentBTN.selected = !cell.voiceCommentBTN.selected;
}

- (void)setTargetInfo:(PAUserInfo *)targetInfo
{
    [self.tradeInfos removeAllObjects];
    NSError *error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:[DocumentsPath stringByAppendingPathComponent:@"mediaComment.amr"] error:&error];
    [[NSFileManager defaultManager] removeItemAtPath:[DocumentsPath stringByAppendingPathComponent:@"mediaComment.wav"] error:&error];
    
    [remitMoneyView.starVoiceBT setBackgroundImage:[UIImage imageNamed:@"pay_voiceStar.png"] forState:UIControlStateNormal];

    [remitMoneyView.historyTradeTAB reloadData];
    _targetInfo = targetInfo;
    [remitMoneyView startAnimition:remitMoneyView.payView];
    if (targetInfo) {
        [self checkUserInfo:targetInfo.phoneNum];
        remitMoneyView.firstTopView.hidden = YES;
        remitMoneyView.havetradeTopView.hidden = NO;
        [self loadTradInfosForSelfAccount:[[[[PADataCenter sharedInstance] selfInfo] baseInfo] account] targetAccount:targetInfo.account];
    }else{
        [navView setTitle:@"手机转账"];
        remitMoneyView.firstTopView.hidden = NO;
        remitMoneyView.havetradeTopView.hidden = YES;
        [self.tradeInfos removeAllObjects];
        [remitMoneyView.historyTradeTAB reloadData];
    }
}
- (void)loadTradInfosForSelfAccount:(NSString *)selfAccount targetAccount:(NSString *)targetAccount
{
    NSString *fileName = [DocumentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@",selfAccount,targetAccount]];
    NSArray *cacheHistoryTradInfos = [NSArray arrayWithContentsOfFile:fileName];
    for (NSDictionary *dic in cacheHistoryTradInfos) {
        PATradeInfo * patradeInfo = [[PATradeInfo alloc] initWithDic:dic];
        [self.tradeInfos addObject:patradeInfo];
    }
    [remitMoneyView.historyTradeTAB reloadData];
    
}
- (void)cacheTradInfosForSelfAccount:(NSString *)selfAccount targetAccount:(NSString *)targetAccount tradeInfos:(NSMutableArray *)tradeInfos
{
    NSString *fileName = [DocumentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@",selfAccount,targetAccount]];
    
    if ([tradeInfos writeToFile:fileName atomically:YES]) {
        NSLog(@"缓存交易记录详情成功");
    }else{
        NSLog(@"缓存交易记录详情失败");
    }
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return TradeInfoCellHeight;
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tradeInfos.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"TradeCell";
    PATradeInfoCell *cell = (PATradeInfoCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell){
        cell = [[PATradeInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        cell.selectionStyle = NO;
        cell.parentController = self;
    }
    PATradeInfo *tradeInfo = [self.tradeInfos objectAtIndex:indexPath.row];
    if(tradeInfo.tradeDirection == TDT_Income) [cell.headIV  setImgUrl:self.targetInfo.headImageUrl key:self.targetInfo.phoneNum digest:self.targetInfo.headImageDigest];
    [cell loadInfo:tradeInfo];
    return cell;
}

#pragma mark - UITextFieldDelegate  methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == remitMoneyView.contextpassTF) {
        [self handleSingleTapFrom:nil];
    }
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    remitMoneyView.historyTradeTAB.frame = CGRectMake(0, 44 + 45, 320, (iPhone5?548:460) - 216 - 112/2 - 44 - 45 + 10);
    [self scrollDown];
    remitMoneyView.recordVoiceBgIV.hidden = NO;
    remitMoneyView.recordVoiceBTN.hidden = NO;
    remitMoneyView.commentLAB.hidden = NO;

    [self startAnimitionT:remitMoneyView.payView snedType:2];
    [self startAnimitionT:remitMoneyView.paypassView snedType:2];

    [textField.text floatValue];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == remitMoneyView.paytoContactTF) {
        NSLog(@"paytoContactTF");
        
    }else if(textField == remitMoneyView.contextTF){
        NSLog(@"contextTF");
    }else if (textField == remitMoneyView.contextpassTF){
        NSLog(@"contextpassTF");
    }
    [textField.text floatValue];
}
//完成 编辑 待支付对象的 电话号码
- (void)targetPhoneEndEdit:(UITextField *)targetPhoneTF
{
    if (targetPhoneTF.text && ![targetPhoneTF.text isEqualToString:@""]) {
        [self checkUserInfo:targetPhoneTF.text];
    }
}
#pragma mark - 生成客户端 trade 标识
- (NSString *)getClientPaymentId
{
    PADataCenter *dataCenter = [PADataCenter sharedInstance];
    NSString *dateStr = [NSString stringWithFormat:@"%g" ,[[NSDate date] timeIntervalSince1970] ];
    return [NSString stringWithFormat:@"%@-%@-%@",dataCenter.selfInfo.baseInfo.account,self.targetInfo.account,dateStr];
}

- (NSUInteger)indexOfLocalWithTradeId:(NSString *)tradeId
{
    NSUInteger index = INT16_MAX;
    for (PATradeInfo *trade in self.tradeInfos) {
        if ([trade.tradeId isEqualToString:tradeId]) {
            index = [self.tradeInfos indexOfObject:trade];
        }
    }
    return index;
}

@end
